// pages/canvas/canvas.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bgWidth: 0,
    bgHeight: 0,
    content: null,//canvas
    theme: 'blue',
    index: 0,
    fc: '#FFFFFF',
    itemlist: [],
    title: "",
    writer: "",
    scale: 0,
    dpr:1,
    flag:false
  },

  canvasRender: function (theme, index) {
    let that = this
    const canvas = this.data.content
    const ctx = canvas.getContext('2d');

    wx.cloud.downloadFile({
      fileID: 'cloud://klein-4gjl255q891ea4a5.6b6c-klein-4gjl255q891ea4a5-1307930023/' + theme + '/' + theme + 'bg' + index + '.png',
      success: res => {
        const bgImg = canvas.createImage();
        bgImg.src = res.tempFilePath;
        
        bgImg.onload = () => {
          ctx.scale(that.data.dpr,that.data.dpr)
          ctx.drawImage(bgImg, 0, 0, parseInt(that.data.bgWidth), parseInt(that.data.bgHeight));
          ctx.fillStyle = that.data.fc;
          this.drawTitle(canvas);
          this.drawList(canvas);
          this.drawWriter(canvas);
        }
      },
      fail: err => {
        console.log("图片获取失败");
      }
    })
  },

  drawTitle: function (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.font = 40 * this.data.scale + 'px Microsoft TaHei';
    ctx.fillText(this.data.title,parseInt(this.data.bgWidth)* 0.9 - ctx.measureText(this.data.title).width, parseInt(this.data.bgHeight) * 0.1);
  },
  drawList: function (canvas) {
    let list = this.data.itemlist
    const ctx = canvas.getContext('2d');
    ctx.font = 28 * this.data.scale + 'px Microsoft TaHei';
    let lineheight = 50 * this.data.scale;
    for (let i = 0; i < list.length; i++) {
      ctx.fillText(list[i], parseInt(this.data.bgWidth) * 0.15, (parseInt(this.data.bgHeight) - list.length * lineheight) * 0.5 + i * lineheight);
    }
  },
  drawWriter: function (canvas) {
    const ctx = canvas.getContext('2d');
    ctx.font = 30 * this.data.scale + 'px Microsoft TaHei';
    ctx.fillText(this.data.writer, parseInt(this.data.bgWidth)* 0.9 - ctx.measureText(this.data.writer).width, parseInt(this.data.bgHeight) * 0.9);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    wx.getSystemInfo({
      success: res => {
        const dpr=res.pixelRatio
        const scale=res.windowWidth / 750  
        that.setData({
          bgWidth:  res.windowHeight * 0.7 * 0.625+ "px",
          bgHeight:  res.windowHeight * 0.7+ "px",
          scale: scale,
          dpr:dpr
        })
      }
    })

    that.setData({
      theme: options.theme,
      index: options.swiperIndex,
      fc: options.fc,
      writer: options.writer,
      title: options.title,
      itemlist: options.itemlist.split(',')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // var that = this;
    // // 使用 wx.createContext 获取绘图上下文 context
    // const query = wx.createSelectorQuery();
    // query.select('#canvas').fields({ node: true, size: true }).exec(res => {
    //   const width = res[0].width;
    //   const height = res[0].height;
    //   const canvas = res[0].node;
    //   canvas.height = height*that.data.dpr;
    //   canvas.width = width*that.data.dpr;

    //   that.setData({
    //     content: canvas
    //   });
    //   that.canvasRender(that.data.theme, that.data.index);
    // })
  },

  openSetting: function () {
    wx.openSetting()
  },
  // 保存图片到相册
  saveimg: function () {
    var that = this;
    const canvas = this.data.content
    const ctx = canvas.getContext('2d');

    //用户授权
    wx.authorize({
      scope: 'scope.writePhotosAlbum',
      //如果有授权
      success: res => {
        wx.canvasToTempFilePath({
          canvas: canvas,
          fileType: 'png',
          //保存过程中没有问题
          success: res => {
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: res => {
                wx.showToast({
                  title: '已保存到相册',
                  icon: 'success',
                  duration: 2000
                })
                that.data.flag=!that.data.flag
              },
              //保存过程出现问题
              fail: err => {
                wx.showToast({
                  title: '图片保存失败',
                  icon: 'error',
                  duration: 2000
                })
              }
            })
          },
          //不可以保存
          fail: err => {
            console.log("图片保存失败");
          }
        })
      },
      //没有授权，去获取授权
      fail: err => {
        wx.showModal({
          title: '图片保存失败',
          content: '您未授权',
          showCancel: false,
          confirmText: '去设置',
          success: res => {
            that.openSetting()
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    // 使用 wx.createContext 获取绘图上下文 context
    const query = wx.createSelectorQuery();
    query.select('#canvas').fields({ node: true, size: true }).exec(res => {
      const width = res[0].width;
      const height = res[0].height;
      const canvas = res[0].node;
      canvas.height = height*that.data.dpr;
      canvas.width = width*that.data.dpr;

      that.setData({
        content: canvas
      });
      that.canvasRender(that.data.theme, that.data.index);
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.data.flag){
      wx.reLaunch({
        url: '/pages/tabBar/find/find',
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})